package l1j.server.server.model.item.funtion;

import l1j.server.configure.Config;
import l1j.server.server.ClientThread;
import l1j.server.server.datatables.LogEnchantTable;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.inventory.L1PcInventory;
import l1j.server.server.model.item.L1ItemId;
import l1j.server.server.random.RandomGenerator;
import l1j.server.server.random.RandomGeneratorFactory;
import l1j.server.server.serverpackets.S_OwnCharStatus;
import l1j.server.server.serverpackets.S_SPMR;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1Armor;

public class Enchant {
	private static RandomGenerator _random = RandomGeneratorFactory.newRandom();
	/**
	 * 방어구 인첸트
	 */
	public static void enchantArmor(L1PcInstance pc, L1ItemInstance l1iteminstance, L1ItemInstance l1iteminstance1, ClientThread client){
		int itemId = l1iteminstance.getItem(). getItemId();
		int safe_enchant = ((L1Armor) l1iteminstance1.getItem()). get_safeenchant();
		int armorId = l1iteminstance1.getItem(). getItemId();
		
		if (l1iteminstance1 == null
				|| l1iteminstance1.getItem(). getType2() != 2) {
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무것도 일어나지 않았습니다.
			return;
		}
		if (safe_enchant < 0) { // 강화 불가
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무것도 일어나지 않았습니다.
			return;
		}
		if (l1iteminstance1.isSealed()) { // 봉인된 장비 강화 불가
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무것도 일어나지 않았습니다.
			return;
		}
		if (armorId == 20161 || armorId >= 21035 && armorId <= 21038) { // 일루젼 방어용 기구
			if (itemId == 40127) { // 일루젼 방어용 기구 강화 스크롤
			} else {
				pc.sendPackets(new S_ServerMessage(79)); // \f1 아무것도 일어나지 않았습니다.
				return;
			}
		}
		if (itemId == 40127) { // 일루젼 방어용 기구 강화 스크롤
			if (armorId == 20161 || armorId >= 21035 && armorId <= 21038) { // 일루젼 방어용 기구
			} else {
				pc.sendPackets(new S_ServerMessage(79)); // \f1 아무것도 일어나지 않았습니다.
				return;
			}
		}

		int enchant_level = l1iteminstance1.getEnchantLevel();
		if (itemId == L1ItemId.C_SCROLL_OF_ENCHANT_ARMOR) { // c-zel
			pc.getInventory(). removeItem(l1iteminstance, 1);
			if (enchant_level < -6) {
				// -7이상은 할 수 없다.
				failureEnchant(pc, l1iteminstance1, client);
			} else {
				SuccessEnchant(pc, l1iteminstance1, client, -1);
			}
		} else if (enchant_level < safe_enchant) {
			pc.getInventory(). removeItem(l1iteminstance, 1);
			SuccessEnchant(pc, l1iteminstance1, client,
					RandomELevel(l1iteminstance1, itemId));
		} else {
			pc.getInventory(). removeItem(l1iteminstance, 1);
			int rnd = _random.nextInt(100) + 1;
			int enchant_chance_armor;
			int enchant_level_tmp;
			if (safe_enchant == 0) { // 뼈, 브락크미스릴용 보정
				enchant_level_tmp = enchant_level + 2;
			} else {
				enchant_level_tmp = enchant_level;
			}
			if (enchant_level >= 9) {
				enchant_chance_armor = (100 + enchant_level_tmp
						* Config.ENCHANT_CHANCE_ARMOR)
						/ (enchant_level_tmp * 2);
			} else {
				enchant_chance_armor = (100 + enchant_level_tmp
						* Config.ENCHANT_CHANCE_ARMOR)
						/ enchant_level_tmp;
			}

			if (rnd < enchant_chance_armor) {
				int randomEnchantLevel = RandomELevel(l1iteminstance1, itemId);
				SuccessEnchant(pc, l1iteminstance1, client, randomEnchantLevel);
			} else if (enchant_level >= 9 && rnd < (enchant_chance_armor * 2)) {
				String item_name_id = l1iteminstance1.getName();
				String pm = "";
				String msg = "";
				if (enchant_level > 0) {
					pm = "+";
				}
				msg = (new StringBuilder()). append(pm + enchant_level)
						. append(" "). append(item_name_id). toString();
				// \f1%0이%2과 강렬하게%1 빛났습니다만, 다행히 무사하게 살았습니다.
				pc.sendPackets(new S_ServerMessage(160, msg, "$252", "$248"));
			} else {
				failureEnchant(pc, l1iteminstance1, client);
			}
		}

	}
	
	/**
	 * 속성 인첸트
	 */
	public static void enchantWeaponAttr(L1PcInstance pc, L1ItemInstance l1iteminstance	, L1ItemInstance l1iteminstance1, ClientThread client){
		int itemId = l1iteminstance.getItem().getItemId();
		
		 // 바람의 무기 강화 스크롤~불의 무기 강화 스크롤
		if (l1iteminstance1 == null	|| l1iteminstance1.getItem(). getType2() != 1) {
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무일도 일어나지 않았습니다.
			return;
		}
		int safeEnchant = l1iteminstance1.getItem(). get_safeenchant();
		if (safeEnchant < 0) { // 강화 불가
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무일도 일어나지 않았습니다.
			return;
		}

		if (l1iteminstance1.isSealed()) { // 봉인된 장비 강화 불가
			pc.sendPackets(new S_ServerMessage(79)); // \f1 아무일도 일어나지 않았습니다.
			return;
		}

		// 0:무속성 1:지 2:화 4:수 8:풍
		int oldAttrEnchantKind = l1iteminstance1.getAttrEnchantKind();
		int oldAttrEnchantLevel = l1iteminstance1.getAttrEnchantLevel();

		boolean isSameAttr = false; // 스크롤과 강화 끝난 속성이 동일한가
		if (itemId == 41429 && oldAttrEnchantKind == 8
				|| itemId == 41430 && oldAttrEnchantKind == 1
				|| itemId == 41431 && oldAttrEnchantKind == 4
				|| itemId == 41432 && oldAttrEnchantKind == 2) { // 같은 속성
			isSameAttr = true;
		}
		if (isSameAttr && oldAttrEnchantLevel >= 3) {
			pc.sendPackets(new S_ServerMessage(1453)); // 더 이상은 강화할 수 없습니다.
			return;
		}

		int rnd = _random.nextInt(100) + 1;
		if (Config.ATTR_ENCHANT_CHANCE >= rnd) {
			pc.sendPackets(new S_ServerMessage(1410, l1iteminstance1.getLogName(), "$245", "$247")); // f1%0에 강력한 마법의 힘이 스며듭니다.
			int newAttrEnchantKind = 0;
			int newAttrEnchantLevel = 0;
			if (isSameAttr) { // 같은 속성이라면+1
				newAttrEnchantLevel = oldAttrEnchantLevel + 1;
			} else { // 다른 속성이라면 1
				newAttrEnchantLevel = 1;
			}
			if (itemId == 41429) { // 풍의 무기 강화 스크롤
				newAttrEnchantKind = 8;
			} else if (itemId == 41430) { // 지의 무기 강화 스크롤
				newAttrEnchantKind = 1;
			} else if (itemId == 41431) { // 수의 무기 강화 스크롤
				newAttrEnchantKind = 4;
			} else if (itemId == 41432) { // 불의 무기 강화 스크롤
				newAttrEnchantKind = 2;
			}
			l1iteminstance1.setAttrEnchantKind(newAttrEnchantKind);
			pc.getInventory(). updateItem(l1iteminstance1,L1PcInventory.COL_ATTR_ENCHANT_KIND);
			pc.getInventory(). saveItem(l1iteminstance1);
			l1iteminstance1.setAttrEnchantLevel(newAttrEnchantLevel);
			pc.getInventory(). updateItem(l1iteminstance1,L1PcInventory.COL_ATTR_ENCHANT_LEVEL);
			pc.getInventory(). saveItem(l1iteminstance1);
		} else {
			pc.sendPackets(new S_ServerMessage(1411, l1iteminstance1.getLogName(),"$245", "$247")); // f1%0에 마법을 비집고 들어갈 수 없습니다.
		}
		pc.getInventory(). removeItem(l1iteminstance, 1);
	
		
	}
	
	public static void enchantWeapon(L1PcInstance pc, L1ItemInstance l1iteminstance, L1ItemInstance l1iteminstance1, ClientThread client){
		int itemId = l1iteminstance.getItem().getItemId();
		int safe_enchant = l1iteminstance1.getItem().get_safeenchant();
		int weaponId = l1iteminstance1.getItem().getItemId();
		int enchant_level = l1iteminstance1.getEnchantLevel();

		if ((l1iteminstance1 == null) || (l1iteminstance1.getItem().getType2() != 1)
			    || (safe_enchant < 0) || l1iteminstance1.isSealed()) {
			pc.sendPackets(new S_ServerMessage(79));
			return;
		}
		if ((weaponId >= 246) && (weaponId <= 249)) {
			if (itemId != L1ItemId.SCROLL_OF_ENCHANT_QUEST_WEAPON) {
				pc.sendPackets(new S_ServerMessage(79));
				return;
			}
		}
		if (itemId == L1ItemId.SCROLL_OF_ENCHANT_QUEST_WEAPON) {
			if ((weaponId < 246) || (weaponId > 249)) {
				pc.sendPackets(new S_ServerMessage(79));
				return;
			}
		}
		if ((weaponId == 36) || (weaponId == 183) || ((weaponId >= 250) && (weaponId <= 255))) {
			if (itemId != 40128) { 
				pc.sendPackets(new S_ServerMessage(79));
				return;
			}
		}
		if (itemId == 40128) {
			if ((weaponId != 36) && (weaponId != 183) && ((weaponId < 250) || (weaponId > 255))) {
				pc.sendPackets(new S_ServerMessage(79));
				return;
			}
		}
		if (itemId == L1ItemId.C_SCROLL_OF_ENCHANT_WEAPON) {
			pc.getInventory(). removeItem(l1iteminstance, 1);
			if (enchant_level < -6) {
				failureEnchant(pc, l1iteminstance1, client);
			} else {
				SuccessEnchant(pc, l1iteminstance1, client, -1);
			}
		}else if (enchant_level < safe_enchant) {
			pc.getInventory(). removeItem(l1iteminstance, 1);
			SuccessEnchant(pc, l1iteminstance1, client, RandomELevel(l1iteminstance1, itemId));
		}else {
			pc.getInventory(). removeItem(l1iteminstance, 1);
			int rnd = _random.nextInt(100) + 1;
			int enchant_chance_wepon;
			if (enchant_level >= 9) {
				enchant_chance_wepon = (100 + 3 * Config.ENCHANT_CHANCE_WEAPON) / 6;
			} else {
				enchant_chance_wepon = (100 + 3 * Config.ENCHANT_CHANCE_WEAPON) / 3;
			}

			if (rnd < enchant_chance_wepon) {
				int randomEnchantLevel = RandomELevel(l1iteminstance1,
						itemId);
				SuccessEnchant(pc, l1iteminstance1, client,
						randomEnchantLevel);
			} else if (enchant_level >= 9
					&& rnd < (enchant_chance_wepon * 2)) {
				// \f1%0이%2과 강렬하게%1 빛났습니다만, 다행히 무사하게 살았습니다.
				pc.sendPackets(new S_ServerMessage(160, l1iteminstance1.getLogName(), "$245", "$248"));
			} else {
				failureEnchant(pc, l1iteminstance1, client);
			}
		}
		
	}
	private static void failureEnchant(L1PcInstance pc, L1ItemInstance item, ClientThread client) {
		String s = "";
		String sa = "";
		int itemType = item.getItem(). getType2();
		String nameId = item.getName();
		String pm = "";
		if (itemType == 1) { // 무기
			if (! item.isIdentified() || item.getEnchantLevel() == 0) {
				s = nameId; // \f1%0이 강렬하게%1 빛난 뒤, 증발하고 있지 않게 됩니다.
				sa = "$245";
			} else {
				if (item.getEnchantLevel() > 0) {
					pm = "+";
				}
				s = (new StringBuilder()). append(pm + item.getEnchantLevel())
						. append(" "). append(nameId). toString(); // \f1%0이 강렬하게%1
				// 빛난 뒤
				// , 증발하고 있지 않게 됩니다.
				sa = "$245";
			}
		} else if (itemType == 2) { // 방어용 기구
			if (! item.isIdentified() || item.getEnchantLevel() == 0) {
				s = nameId; // \f1%0이 강렬하게%1 빛난 뒤, 증발하고 있지 않게 됩니다.
				sa = " $252";
			} else {
				if (item.getEnchantLevel() > 0) {
					pm = "+";
				}
				s = (new StringBuilder()). append(pm + item.getEnchantLevel())
						. append(" "). append(nameId). toString(); // \f1%0이 강렬하게%1
				// 빛난 뒤
				// , 증발하고 있지 않게 됩니다.
				sa = " $252";
			}
		}
		pc.sendPackets(new S_ServerMessage(164, s, sa));
		pc.getInventory(). removeItem(item, item.getCount());
	}
	
	private static void SuccessEnchant(L1PcInstance pc, L1ItemInstance item, ClientThread client, int i) {
		String s = "";
		String sa = "";
		String sb = "";
		String s1 = item.getName();
		String pm = "";
		if (item.getEnchantLevel() > 0) {
			pm = "+";
		}
		if (item.getItem(). getType2() == 1) {
			if (! item.isIdentified() || item.getEnchantLevel() == 0) {
				switch (i) {
				case -1:
					s = s1;
					sa = "$246";
					sb = "$247";
					break;

				case 1: // '\001'
					s = s1;
					sa = "$245";
					sb = "$247";
					break;

				case 2: // '\002'
					s = s1;
					sa = "$245";
					sb = "$248";
					break;

				case 3: // '\003'
					s = s1;
					sa = "$245";
					sb = "$248";
					break;
				}
			} else {
				switch (i) {
				case -1:
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$246";
					sb = "$247";
					break;

				case 1: // '\001'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$245";
					sb = "$247";
					break;

				case 2: // '\002'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$245";
					sb = "$248";
					break;

				case 3: // '\003'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$245";
					sb = "$248";
					break;
				}
			}
		} else if (item.getItem(). getType2() == 2) {
			if (! item.isIdentified() || item.getEnchantLevel() == 0) {
				switch (i) {
				case -1:
					s = s1;
					sa = "$246";
					sb = "$247";
					break;

				case 1: // '\001'
					s = s1;
					sa = "$252";
					sb = "$247 ";
					break;

				case 2: // '\002'
					s = s1;
					sa = "$252";
					sb = "$248 ";
					break;

				case 3: // '\003'
					s = s1;
					sa = "$252";
					sb = "$248 ";
					break;
				}
			} else {
				switch (i) {
				case -1:
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$246";
					sb = "$247";
					break;

				case 1: // '\001'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$252";
					sb = "$247 ";
					break;

				case 2: // '\002'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$252";
					sb = "$248 ";
					break;

				case 3: // '\003'
					s = (new StringBuilder()). append(
							pm + item.getEnchantLevel()). append(" "). append(s1)
							. toString(); // \f1%0이%2%1 빛납니다.
					sa = "$252";
					sb = "$248 ";
					break;
				}
			}
		}
		pc.sendPackets(new S_ServerMessage(161, s, sa, sb));
		int oldEnchantLvl = item.getEnchantLevel();
		int newEnchantLvl = item.getEnchantLevel() + i;
		int safe_enchant = item.getItem(). get_safeenchant();
		item.setEnchantLevel(newEnchantLvl);
		client.getActiveChar(). getInventory(). updateItem(item,
				L1PcInventory.COL_ENCHANTLVL);
		if (newEnchantLvl > safe_enchant) {
			client.getActiveChar(). getInventory(). saveItem(item);
		}
		if (item.getItem(). getType2() == 1
				&& Config.LOGGING_WEAPON_ENCHANT != 0) {
			if (safe_enchant == 0
					|| newEnchantLvl >= Config.LOGGING_WEAPON_ENCHANT) {
				LogEnchantTable logenchant = new LogEnchantTable();
				logenchant.storeLogEnchant(pc.getId(), item.getId(),
						oldEnchantLvl, newEnchantLvl);
			}
		}
		if (item.getItem(). getType2() == 2 && Config.LOGGING_ARMOR_ENCHANT != 0) {
			if (safe_enchant == 0
					|| newEnchantLvl >= Config.LOGGING_ARMOR_ENCHANT) {
				LogEnchantTable logenchant = new LogEnchantTable();
				logenchant.storeLogEnchant(pc.getId(), item.getId(),
						oldEnchantLvl, newEnchantLvl);
			}
		}

		if (item.getItem(). getType2() == 2) {
			if (item.isEquipped()) {
				pc.addAc(-i);
				int i2 = item.getItem(). getItemId();
				if (i2 == 20011 || i2 == 20110 || i2 == 21108 || i2 == 120011) { // 마직크헤룸, 매직 체인 메일, 캐릭터명의 마법 저항의 T셔츠
					pc.addMr(i);
					pc.sendPackets(new S_SPMR(pc));
				}
				if (i2 == 20056 || i2 == 120056 || i2 == 220056) { // 매직 클로크
					pc.addMr(i * 2);
					pc.sendPackets(new S_SPMR(pc));
				}
			}
			pc.sendPackets(new S_OwnCharStatus(pc));
		}
	}
	
	
	private static int RandomELevel(L1ItemInstance item, int itemId) {
		if (itemId == L1ItemId.B_SCROLL_OF_ENCHANT_ARMOR
				|| itemId == L1ItemId.B_SCROLL_OF_ENCHANT_WEAPON
				|| itemId == 140129 || itemId == 140130) {
			if (item.getEnchantLevel() <= 2) {
				int j = _random.nextInt(100) + 1;
				if (j < 32) {
					return 1;
				} else if (j >= 33 && j <= 76) {
					return 2;
				} else if (j >= 77 && j <= 100) {
					return 3;
				}
			} else if (item.getEnchantLevel() >= 3
					&& item.getEnchantLevel() <= 5) {
				int j = _random.nextInt(100) + 1;
				if (j < 50) {
					return 2;
				} else {
					return 1;
				}
			}
			{
				return 1;
			}
		}
		return 1;
	}
	
}
